package com.wg.es.controller;

import com.alibaba.fastjson.JSONObject;
import com.wg.es.model.DataResponse;
import com.wg.es.service.HistoryDataService;
import com.wg.es.service.RealDataService;
import com.wg.es.utils.HexStringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * Created by xiaoq on 2019-03-13 11:21.
 */
@RestController
@RequestMapping("dataService")
public class DataShareController {


    @Autowired
    RealDataService realDataService;

    @Autowired
    HistoryDataService historyDataService;


    @RequestMapping("realData")
    public String realDataAPI(@RequestBody String jsonParams) {
        JSONObject json = JSONObject.parseObject(jsonParams);
        String station = json.getString("station");
        List<String> indexList = json.getJSONArray("indexList").toJavaList(String.class);
        indexList.add(0,"station_no");
        indexList.add(1,"station");
        indexList.add("pubTime");
        String patton= "ST=22;CN=2011;PW=123456;MN=78170566BJ%s;CP=&&PubTime=%s00;PM10=%s;PM25=%s;SO2=%s;NO2=%s;CO=%s;O3=%s;AQI=%s&&";

        DataResponse response =  realDataService.searchPollution(station,indexList.toArray(new String[]{}));

        JSONObject jsn = JSONObject.parseObject(JSONObject.toJSONString(response));
        JSONObject body = jsn.getJSONArray("body").getJSONObject(0);
        String stationNo = body.getString("station_no");
        String aqi = body.getString("aqi");
        String so2 = body.getString("so2");
        String co = body.getString("co");
        String no2 = body.getString("no2");
        String o3 = body.getString("o3");
        String pm10 = body.getString("pm10");
        String pm2_5 = body.getString("pm2_5");
        String pubTime = body.getString("pubTime");
        String res = String.format(patton,stationNo,pubTime,pm10,pm2_5,so2,no2,co,o3,aqi);
        res = res.replaceAll("-","").replaceAll(":","").replaceAll(" ","");
        String[] arr= res.split("&&");
        String pre = arr[0]+"&&"+arr[1]+"&&";
        String len = String.valueOf(pre.length());
        while (len.length()<4){
            len = "0"+len;
        }
        return "##"+len+res+ HexStringUtil.toHexString(arr[1]);
    }

    @RequestMapping("historyData")
    public DataResponse historyDataAPI(@RequestBody String jsonParams) {
        return historyDataService.queryFromES(jsonParams);
    }
}
